package com.higold.cloud.ui.fragment

import android.os.Bundle
import android.os.Handler
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.higold.cloud.R
import com.higold.cloud.base.BaseFragment
import com.higold.cloud.mvp.contract.RegionalContract
import com.higold.cloud.mvp.model.bean.regionalList.Data
import com.higold.cloud.mvp.model.bean.regionalList.RegionalList
import com.higold.cloud.mvp.presenter.RegionalPresenter
import com.higold.cloud.net.exception.ErrorStatus
import com.higold.cloud.showToast
import com.higold.cloud.ui.adapter.RegionalAdapter
import com.higold.cloud.view.recyclerview.ReportItem
import com.higold.cloud.view.recyclerview.adapter.ExpandReportItem
import kotlinx.android.synthetic.main.fragment_regional.*


/**
 *    author : lxz
 *    date   : 2019/8/12 14:36
 *    desc   :
 */
class RegionalFragment : BaseFragment(), RegionalContract.View, BaseQuickAdapter.RequestLoadMoreListener {

    private var mTitle: String? = null

    private val mPresenter by lazy { RegionalPresenter() }

    private var isFirst: Boolean = true

    private lateinit var adapter: RegionalAdapter

    private var regionalList: RegionalList? = null

    private lateinit var list: ArrayList<MultiItemEntity>

    private val delayMillis = 1500

    private var mCurrentCounter = 0

    private var isErr: Boolean = false

    private var mLoadMoreEndGone = false

    init {
        mPresenter.attachView(this)
    }

    companion object {
        private val TOTAL_COUNTER = 15
        private val PAGE_SIZE = 5
        fun getInstance(title: String): RegionalFragment {
            val fragment = RegionalFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_regional

    override fun lazyLoad() {
        mPresenter.requestRegionalList()
    }

    override fun setRegionalList(regionalList: RegionalList) {
        this.regionalList = regionalList
        multipleStatusView.showContent()
        setAdapter(regionalList)
    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR) {
            multipleStatusView.showNoNetwork()
        } else {
            multipleStatusView.showError()
        }
    }

    override fun showLoading() {
        multipleStatusView.showLoading()
    }

    override fun dismissLoading() {

    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
    }

    override fun initView() {

        refreshLayout.setOnRefreshListener {
            adapter.setEnableLoadMore(false)
            Handler().postDelayed({

                mPresenter.requestRegionalList()
                isErr = false
                mCurrentCounter = PAGE_SIZE
                adapter.setEnableLoadMore(true)
            }, delayMillis.toLong())
        }
//        refreshLayout.autoRefresh()
    }

    override fun onLoadMoreRequested() {
        refreshLayout.isEnableRefresh = false
        if (adapter.data.size < PAGE_SIZE) {
            adapter.loadMoreEnd(true)
        } else {
            if (mCurrentCounter >= TOTAL_COUNTER) {
                adapter.loadMoreEnd(mLoadMoreEndGone)
            } else {
                if (!isErr) {
                    list.addAll(generateData(regionalList!!.data))
                    adapter.notifyLoadMoreToLoading()
                    adapter.expandAll()
                    mCurrentCounter = adapter.data.size
                    adapter.loadMoreComplete()
                } else {
                    isErr = true
                    showToast("网络错误！")
                    adapter.loadMoreFail()
                }
            }
            refreshLayout.isEnableRefresh = true
        }
    }

    private fun setAdapter(regionalList: RegionalList) {

        if (refreshLayout.isRefreshing) {
            refreshLayout.finishRefresh()
            list = generateData(regionalList.data)
            adapter.notifyDataSetChanged()
            rv_regional.scheduleLayoutAnimation()
        } else {
            list = generateData(regionalList.data)
            adapter = RegionalAdapter(list)
            adapter.setOnLoadMoreListener(this, rv_regional)
            adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT)
            val manager = GridLayoutManager(activity, 3)
            manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return manager.spanCount
                }
            }

            rv_regional.adapter = adapter
            // important! setLayoutManager should be called after setAdapter
            rv_regional.layoutManager = manager
            adapter.expandAll()
        }
    }


    private fun generateData(list: ArrayList<Data>): ArrayList<MultiItemEntity> {
        isFirst = false
        val res = ArrayList<MultiItemEntity>()
        for (i in 0 until list.size) {
            val data = list[i]
            for (j in 0 until data.child.size) {
                data.addSubItem(data.child[j])
            }
            res.add(data)
        }
        return res
    }
}